package com.example.myapplication1.ui.home;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.example.myapplication1.Adapter.ChatitemAdapter;
import com.example.myapplication1.Bean.ChatItem;
import com.example.myapplication1.Bean.Msg;
import com.example.myapplication1.Bean.User;
import com.example.myapplication1.R;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment {
    private ListView chatitmelv;
    ChatitemAdapter adapter;
    //辨别取三个表格里的数据
    List<ChatItem>chatItemList=new ArrayList<>();
    List<User>userList=new ArrayList<>();
    List<Msg>msgList=new ArrayList<>();
    int myid;
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_home, container, false);
         initView(root);
         initData();
        return root;
    }
    private void initData() {
        SharedPreferences sp=getActivity().getSharedPreferences("userinfo", Context.MODE_PRIVATE);
        myid=sp.getInt("myid",-1);
        userList= LitePal.where("id != ?",myid+"").find(User.class);//封装数据
        //对用户列表聊天的限制
        for (User u:userList){
            msgList=getChatContext(u);//获取聊天内容
            Log.e("msgsize",msgList.size()+"");
            if(msgList.size()!=0){
                Msg msg=msgList.get(msgList.size()-1);
                ChatItem chatItem=new ChatItem(u.getUsering(),u.getName(),msg.getContent(),msg.getDate());
                chatItemList.add(chatItem);
            }
        }
    }
    private List<Msg> getChatContext(User u) {
        List<Msg> msgs=new ArrayList<>();
        for (Msg m:LitePal.findAll(Msg.class)){
            boolean a= myid==m.getSend_id()&&u.getId()==m.getReceive_id();//接受
            boolean b= myid==m.getReceive_id()&&u.getId()==m.getSend_id();
            if (a||b){
                msgs.add(m);
            }
        }
        return  msgs;
    }

    private void initView(View root){
        chatitmelv=root.findViewById(R.id.text_home);
        adapter=new ChatitemAdapter(getContext(),R.layout.chat_item,chatItemList);
        chatitmelv.setAdapter(adapter);
    }
}